import axios from 'axios';
import store from '@/store/index'
import {MessageBox} from "element-ui";
import router from '@/router'
axios.defaults.timeout = 12000; // 请求超时时间

/** 区分打包环境与开发环境
 * process.env.NODE_ENV==='production'  (打包环境)
 * process.env.NODE_ENV==='development' (开发环境)
 */

axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? 'http://www.webzzw.xyz/django_api/' : "/django_api"

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8' // post请求头的设置

// 添加请求拦截器
axios.interceptors.request.use(
    config => {
        // 在发送请求之前做些什么
        store.commit('loading/setLoading',true)
        let token = store.getters['user/getToken']
        if (token) config.headers.token = token
        return config;
    },
    error => {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
)

// 添加响应拦截器
axios.interceptors.response.use(
    response => {
        store.commit('loading/setLoading',false)
        // 对响应数据做点什么
        if (response.data.code === 'no token'){
            store.dispatch('user/logout',()=>{
                MessageBox.alert(response.data.msg,{
                    title:'提示',
                    type:'error',
                    callback: () => router.push('/')
                })
            })
            return Promise.reject(response.data.msg)
        }

        return Promise.resolve(response)

    },
    error => {
        // 对响应错误做点什么
        const responseCode = error.response.status
        switch (responseCode) {
            case 401:
                break
            case 404:
                alert('网络请求不存在')
                break
            default:
                alert(error.response.data.message)
        }
        return Promise.reject(error)
    }
)

class Index {
    get(url, params = {}) {
        return new Promise((resolve, reject) => {
            axios.get(url, {params})
                .then(res => resolve(res.data))
                .catch(err => reject(err.data))
        })
    }

    post(url, params = {}) {
        return new Promise((resolve, reject) => {
            axios.post(url, params)
                .then(res => resolve(res.data))
                .catch(err => reject(err))
        })
    }

    put(url, params = {}) {
        return new Promise((resolve, reject) => {
            axios.put(url, params)
                .then(res => resolve(res.data))
                .catch(err => reject(err))
        })
    }

    delete(url, params = {}) {
        return new Promise((resolve, reject) => {
            axios.delete(url, params)
                .then(res => resolve(res.data))
                .catch(err => reject(err))
        })
    }
}

export default new Index()
